package org.rui.rpc.protocol;

import io.vertx.core.buffer.Buffer;
import org.rui.rpc.enums.ProtocolMessageSerializerEnum;
import org.rui.rpc.serializer.Serializer;
import org.rui.rpc.serializer.SerializerFactory;

import java.io.IOException;

/**
 * @author: linweirui
 * @date: 2024/12/09 10:16
 */

/**
 * 协议消息编码器
 */
public class ProtocolMessageEncoder {
    public static Buffer encode(ProtocolMessage<?> protocolMessage) throws IOException {
        if(protocolMessage == null || protocolMessage.getHeader() == null){
            return Buffer.buffer();
        }
        ProtocolMessage.Header header = protocolMessage.getHeader();
        //依次向缓冲区写入字节
        Buffer buffer = Buffer.buffer();
        buffer.appendByte(header.getMagic());
        buffer.appendByte(header.getVersion());
        buffer.appendByte(header.getSerializer());
        buffer.appendByte(header.getType());
        buffer.appendByte(header.getStatus());
        buffer.appendLong(header.getRequestId());
        //获取序列化器
        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getMessageSerializerByValue(header.getSerializer());
        if(serializerEnum == null){
            throw new RuntimeException("序列化协议不存在");
        }
        Serializer serializer = SerializerFactory.getSerializer(serializerEnum.getText());

        byte[] bodyBytes = serializer.serialize(protocolMessage.getBody());
        //写入长度和数据
        buffer.appendInt(bodyBytes.length);
        buffer.appendBytes(bodyBytes);
        return buffer;
    }
}
